package com.dtborad.myblog.controller;

import com.dtborad.myblog.common.CommonErrorCode;
import com.dtborad.myblog.common.Result;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

@Slf4j
@Api(tags = "头像上传")
@RestController
@RequestMapping("/upload")
public class AvatarController {

    private static final String UPLOAD_DIR = "fileStore";

    private static List<String> IMAGE_EXTENSIONS = Arrays.asList("jpg", "jpeg", "png", "webp");

    // 头像上传接口
    @PostMapping("/avatar")
    public Result<String> uploadAvatar(@RequestParam MultipartFile file) {
        //判断file类型是否是图片格式
        String fileExtension = getFileExtension(file.getOriginalFilename());
        if (!IMAGE_EXTENSIONS.contains(fileExtension.toLowerCase())) {
            return Result.ofFail(CommonErrorCode.UNSUPPORTED_FILE_TYPES);
        }
        try {
            // 处理上传逻辑，将头像保存到本地或云存储中
            String filePath = saveAvatar(file);
            // 返回上传结果
            return Result.ofSuccess(filePath);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.ofFail(CommonErrorCode.IO_ERROR);
        }
    }


    private String getFileExtension(String fileName) {
        return fileName.substring(fileName.lastIndexOf('.') + 1);
    }

    private String saveAvatar(MultipartFile file) throws IOException {
        String originalFileName = file.getOriginalFilename();
        String fileExtension = originalFileName.substring(originalFileName.lastIndexOf("."));
        String uniqueFileName = UUID.randomUUID() + fileExtension; // 使用 UUID 生成唯一文件名
        // 获取类路径
        URI uri = null;
        try {
            uri = getClass().getClassLoader().getResource("").toURI();
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }
        Path classpath = Paths.get(uri).toAbsolutePath();

        // 构建文件存储目录路径
        String fileStorePath = classpath.resolveSibling(UPLOAD_DIR).toString();
        Path uploadPath = Paths.get(fileStorePath);
        if (!Files.exists(uploadPath)) {
            Files.createDirectories(uploadPath);
        }
        Path filePath = uploadPath.resolve(uniqueFileName);
        Files.copy(file.getInputStream(), filePath);
        return UPLOAD_DIR + uniqueFileName;
    }

}
